﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Art_To_Eagle.Lib.Windows
{
    /// <summary>
    /// DownloadItem.xaml 的交互逻辑
    /// </summary>
    public partial class DownloadItem : UserControl
    {
        private readonly DownloadImage DL;

        public DownloadItem(DownloadImage item, ImageSource pic = null)
        {
            DL = item;
            InitializeComponent();
            Loaded += (o, e) =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Filename.Content = item.Info.Name;
                    if (pic != null)
                        ViewImage.Source = pic;
                });
            };
            Task.Factory.StartNew(() =>
            {
                while (DL.Exception == null & DL.Result == null & !DL.ShutdownFlag)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Progress.Maximum = DL.TotalBytes == 0 ? 1 : DL.TotalBytes;
                        Progress.Value = DL.ReceivedBytes;
                        ProgressNumber.Content = (int)(DL.Progress * 100) + "%";
                    });
                    Thread.Sleep(500);
                }
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Progress.Maximum = DL.TotalBytes == 0 ? 1 : DL.TotalBytes;
                    Progress.Value = DL.ReceivedBytes;
                    ProgressNumber.Content = (int)(DL.Progress * 100) + "%";
                    if (DL.Exception != null)
                        Task.Run(() => MessageBox.Show(DL.Info.Name + "下载失败\n" + DL.Exception.Message));
                    ((MainWindow)Application.Current.MainWindow).DownloadListBox.Items.Remove(this);
                });
            });
        }

        private void ShutdownTask(object sender, RoutedEventArgs e) => DL.Shutdown();
    }
}
